package com.mycase.im.boot.utils;

import com.mycase.im.boot.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件操作类
 * @Author ZhuHJay
 * @Date 2021/10/22 14:38
 */
@Slf4j
@Component
public class FileLoadUtil {


    public String fileUpload(MultipartFile file, String uploadPath, String[] types){
        // 判断文件类型是否匹配
        String suf = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        log.warn("上传文件的类型为: {}", suf);
        log.warn("上传路径为: {}", uploadPath);
        boolean isPass = false;
        for (String type : types) {
            if( type.equalsIgnoreCase(suf) ){
                isPass = true;
                break;
            }
        }
        if( !isPass ){
            throw new CustomException("上传文件的类型不匹配, 请重试");
        }
        String fileName = UUIDUtil.getUUID() + "." + suf;
        try {
            file.transferTo(new File(uploadPath + "/" + fileName));
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("修改错误, 请重试");
        }
        return fileName;
    }

}
